package vip.meeet.thread.base;


/**
 * threadlocal:
 * https://www.zhihu.com/question/341005993
 * https://zhuanlan.zhihu.com/p/192997550
 *
 * 应用场景：
 * 1. Session
 * 2. Connection
 * 3.SimplateDateFormat
 * 4. Spring 事务管理器
 * 5. Spring MVC 的 RequestContextHolder
 * 6. 存放线程共享变量如token
 *
 * Hash冲突解决方法：
 * 1. 再hash，如果有hash值，就重新计算hash
 * 2. 开放地址(闭散法)，如果hash已经存在，则找前面或者后面的位置
 * 3. 建立公共溢出区：把冲突hash放在另一块溢出区
 * 4. 链式地址法：冲突hash用链表存储，HashMap
 */
public class ThreadLocalStart {

    private static ThreadLocal<Integer> seqNum = new ThreadLocal<Integer>(){
        public Integer initialValue(){
            return 0;
        }
    };

    public static void main(String[] args) throws InterruptedException {
        final ThreadLocal<String> threadLocal = new ThreadLocal<>();
        threadLocal.set("main-thread : Hello");

        Thread thread = new Thread(() -> {
            // 获取不到主线程设置的值，所以为null
            System.out.println(threadLocal.get());
            threadLocal.set("sub-thread : World");
            System.out.println(threadLocal.get());
        });
        // 启动子线程
        thread.start();
        // 让子线程先执行完成，再继续执行主线
        thread.join();
        // 获取到的是主线程设置的值，而不是子线程设置的
        System.out.println(threadLocal.get());
        threadLocal.remove();
        System.out.println(threadLocal.get());
    }

    private static void oom(){//解决内存泄漏
        ThreadLocal<String> localName = new ThreadLocal();
        try {
            localName.set("张三");
        } finally {
            localName.remove();
        }
    }
}
